package vip.xiaonuo.sys.modular.question.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.sys.modular.question.entity.Examinationrecord;
import vip.xiaonuo.sys.modular.question.entity.Testpaper;
import vip.xiaonuo.sys.modular.question.entity.Testpapermx;
import vip.xiaonuo.sys.modular.question.enums.TestpaperExceptionEnum;
import vip.xiaonuo.sys.modular.question.mapper.*;
import vip.xiaonuo.sys.modular.question.param.TestpaperParam;
import vip.xiaonuo.sys.modular.question.service.TestpaperService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 问卷列表service接口实现类
 *
 * @author lxc
 * @date 2024-03-04 11:34:58
 */
@Service
public class TestpaperServiceImpl extends ServiceImpl<TestpaperMapper, Testpaper> implements TestpaperService {
    @Resource
    private TestpaperMapper testpaperMapper;
    @Resource
    private TestpapermxMapper testpapermxMapper;
    @Resource
    private ExaminationrecordMapper examinationrecordMapper;
    @Resource
    private BigquestionfoMapper bigquestionfoMapper;
    @Resource
    private SmallquestionfoMapper smallquestionfoMapper;

    @Override
    public PageResult<Testpaper> page(TestpaperParam testpaperParam) {
        QueryWrapper<Testpaper> queryWrapper = new QueryWrapper<>();
        boolean isAdmin = LoginContextHolder.me().isSuperAdmin();
        if (ObjectUtil.isNotNull(testpaperParam)) {

            // 根据试卷名称 查询
            if (ObjectUtil.isNotEmpty(testpaperParam.getTitle())) {
                queryWrapper.lambda().like(Testpaper::getTitle, testpaperParam.getTitle());
            }
            // 根据试卷类型 查询
            if (ObjectUtil.isNotEmpty(testpaperParam.getPapertype())) {
                queryWrapper.lambda().like(Testpaper::getPapertype, testpaperParam.getPapertype());
            }
            // 根据编辑时间 查询
            if (ObjectUtil.isNotEmpty(testpaperParam.getEtime())) {
                queryWrapper.lambda().eq(Testpaper::getEtime, testpaperParam.getEtime());
            }
            // 根据考试对象 查询
            if (ObjectUtil.isNotEmpty(testpaperParam.getExaminee())) {
                queryWrapper.lambda().eq(Testpaper::getExaminee, testpaperParam.getExaminee());
            }
            if (ObjectUtil.isNotEmpty(testpaperParam.getState())) {
                queryWrapper.lambda().eq(Testpaper::getState, testpaperParam.getState());
            }
            if (!isAdmin) {
                SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
                // 根据试卷状态 查询,判断是否发放，
                queryWrapper.lambda().eq(Testpaper::getState, "release");
                Long orgId = LoginContextHolder.me().getSysLoginUser().getLoginEmpInfo().getOrgId();
                //String roleId = String.valueOf(dicts.get(0).get("id"));
                //queryWrapper.and(q->q.like("exam_testpaper.examinee",roleId));
                queryWrapper.and(q -> q.like("exam_testpaper.personnelid", orgId));
                //queryWrapper.or().like("exam_testpaper.examinee","");
                queryWrapper.or(q -> q.eq("exam_testpaper.personnelid", ""));
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public PageResult<Examinationrecord> pageRecorde(Examinationrecord examinationrecord) {
        QueryWrapper<Examinationrecord> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(examinationrecord)) {
            if (ObjectUtil.isNotEmpty(examinationrecord.getTitle())) {
                queryWrapper.lambda().eq(Examinationrecord::getTitle, examinationrecord.getTitle());
            }
            if (ObjectUtil.isNotEmpty(examinationrecord.getUsername())) {
                queryWrapper.lambda().eq(Examinationrecord::getUsername, examinationrecord.getUsername());
            }
        }
        return new PageResult<>(examinationrecordMapper.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Testpaper> list(TestpaperParam testpaperParam) {
        return this.list();
    }

    @Override
    public void add(TestpaperParam testpaperParam) {
        //保存问卷
        Testpaper testpaper = new Testpaper();
        BeanUtil.copyProperties(testpaperParam, testpaper);
        testpaper.setState("edit");
        this.save(testpaper);
        //保存问卷题型
        List<Testpapermx> list = testpaperParam.getTestpapermxList();
        for (Testpapermx testpapermx : list) {
            testpapermx.setTestpaperId(testpaper.getTestpaperId());
            testpapermxMapper.insert(testpapermx);
        }

    }

    @Override
    public Examinationrecord addRecord(Examinationrecord examinationrecord) {
        examinationrecord.setCtime(new Date());
        //获取当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        examinationrecord.setUsername(sysLoginUser.getUsername());
        examinationrecord.setUserId(sysLoginUser.getId());
        examinationrecordMapper.insert(examinationrecord);
        return examinationrecord;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TestpaperParam> testpaperParamList) {
        testpaperParamList.forEach(testpaperParam -> {
            Testpaper testpaper = this.queryTestpaper(testpaperParam);
            this.removeById(testpaper.getTestpaperId());
            //删除明细
            testpapermxMapper.deleteByTestId(testpaper.getTestpaperId());
            //删除对应的选项
            bigquestionfoMapper.deleteByTestId(testpaper.getTestpaperId());
            //删除对应的选项
            smallquestionfoMapper.deleteByTestId(testpaper.getTestpaperId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TestpaperParam testpaperParam) {
        Testpaper testpaper = this.queryTestpaper(testpaperParam);
        List<Long> orgList = testpaperParam.getGrantOrgIdList();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < orgList.size(); i++) {
            stringBuilder.append(orgList.get(i));
            stringBuilder.append(";");
        }
        testpaperParam.setPersonnelid(stringBuilder.toString());
        BeanUtil.copyProperties(testpaperParam, testpaper);
        testpaper.setState("edit");
        this.updateById(testpaper);
        boolean bol = testpapermxMapper.deleteByTestId(testpaper.getTestpaperId());
        List<Testpapermx> list = testpaperParam.getTestpapermxList();
        if (list != null) {
            for (Testpapermx testpapermx : list) {
                testpapermx.setTestpaperId(testpaper.getTestpaperId());
                testpapermxMapper.insert(testpapermx);
            }
        }
    }

    @Override
    public List<Testpapermx> detail(TestpaperParam testpaperParam) {
        return testpapermxMapper.selectByTestId(testpaperParam.getTestpaperId());
    }

    /**
     * 获取问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    private Testpaper queryTestpaper(TestpaperParam testpaperParam) {
        Testpaper testpaper = this.getById(testpaperParam.getTestpaperId());
        if (ObjectUtil.isNull(testpaper)) {
            throw new ServiceException(TestpaperExceptionEnum.NOT_EXIST);
        }
        return testpaper;
    }

    public List<Map<String, Object>> getSjData(Map<String, Object> map) {
        return testpaperMapper.getSjDataMap(map);
    }

    /**
     * @param testpaper
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editState(Testpaper testpaper) {
        testpaper.setUpdateTime(new Date());
        testpaperMapper.updateState(testpaper);
    }

    @Override
    public List<Map<String, Object>> surveyInfo(Long orgId) {
        List<Map<String, Object>> mapList = testpaperMapper.surveyInfo(orgId);
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < mapList.size(); i++) {
            String count = mapList.get(i).get("COUNT").toString();
            Object leveltrain = mapList.get(i).get("LEVELTRAIN");
            mapList.get(i).put("value", count);
            if ("".equals(leveltrain) || leveltrain == null) {
                mapList.get(i).put("name", "其他");
            } else {
                mapList.get(i).put("name", leveltrain.toString());
            }
        }
        return mapList;
    }

    @Override
    public List<List<String>> surveyInfoDetail() {
        List<Map<String, Object>> mapList = testpaperMapper.surveyInfoDetail();
        List<List<String>> lists = dataInfo(mapList);
        return lists;
    }

    /**
     * 数据处理
     */
    public List<List<String>> dataInfo(List<Map<String, Object>> mapList) {
        List<List<String>> arrayList = new ArrayList<>();
        String titles = "";
        List list1 = new ArrayList();
        list1.add("product");
        list1.add("好");
        list1.add("较好");
        list1.add("一般");
        list1.add("不好");
        arrayList.add(list1);
        List list = new ArrayList();
        String testpaperId = "";
        for (int i = 0; i < mapList.size(); i++) {
            String title = mapList.get(i).get("title").toString();
            String count = mapList.get(i).get("count").toString();
            testpaperId = mapList.get(i).get("testpaperId").toString();
            if ("".equals(titles)) {
                titles = title;
            }
            if (titles.equals(title)) {//判断部门名称是否一致
                if (list.contains(title)) {//判断集合中是否存在对应名称，不能重复
                    list.add(count);
                } else {
                    //不存在则添加名称和数量
                    list.add(title);
                    list.add(count);
                }
            } else {
                titles = title;
                if (list.size() == 4) {
                    testpaperId = mapList.get(i - 1).get("testpaperId").toString();
                    list.add(0);
                    list.add(testpaperId);
                } else if (list.size() == 3) {
                    testpaperId = mapList.get(i - 1).get("testpaperId").toString();
                    list.add(0);
                    list.add(0);
                    list.add(testpaperId);
                } else if (list.size() == 2) {
                    testpaperId = mapList.get(i - 1).get("testpaperId").toString();
                    list.add(0);
                    list.add(0);
                    list.add(0);
                    list.add(testpaperId);
                } else {
                    list.add(testpaperId);
                }
                arrayList.add(list);
                list = new ArrayList();
                testpaperId = mapList.get(i).get("testpaperId").toString();
                list.add(title);
                list.add(count);
            }
        }
        if (list.size() == 2) {
            list.add(0);
            list.add(0);
            list.add(0);
            list.add(testpaperId);
        } else if (list.size() == 3) {
            list.add(0);
            list.add(0);
            list.add(testpaperId);
        } else if (list.size() == 4) {
            list.add(0);
            list.add(testpaperId);
        } else {
            list.add(testpaperId);
        }
        arrayList.add(list);
        return arrayList;
    }

    @Override
    public List<Map<String, Object>> progressDetail() {
        List list = testpaperMapper.userDetail();
        return list;
    }

    @Override
    public List<Testpaper> getSurver(Testpaper testpaper) {
        return testpaperMapper.getSurver();
    }

    @Override
    public List<Map<String, Object>> queryIsAnswer(Examinationrecord examinationrecord) {
        return testpaperMapper.queryIsAnswer(examinationrecord);
    }

    @Override
    public List<String> queryOrgNames(String testpaperId) {
        List<Map<String, Object>> maps = testpaperMapper.queryOrgNames(testpaperId);
        if (maps != null && !maps.isEmpty()) {
            return maps.stream().map(m -> MapUtil.getStr(m, "NAME")).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public List<Map<String, Object>> statisticsInfo(String testpaperId, Long orgId) {

        List<Map<String, Object>> maps = testpaperMapper.statisticsInfo(testpaperId, orgId);

        List<Map<String, Object>> result = new ArrayList<>();
        List<String> quertionsIds = new ArrayList<>();
        for (Map<String, Object> map : maps) {

            String questionsId = ObjectUtil.toString(map.get("QUESTIONS_ID"));
            if (quertionsIds.contains(questionsId)) {
                continue;
            }
            quertionsIds.add(questionsId);
            String title = ObjectUtil.toString(map.get("TITLE"));

            int sumA = maps.stream().filter(item ->
                    StringUtils.equals(questionsId, ObjectUtil.toString(item.get("QUESTIONS_ID"))) && StringUtils.equals("A", ObjectUtil.toString(item.get("USERANSWER")))
            ).mapToInt(item -> Integer.parseInt(ObjectUtil.toString(item.get("COUNT")))).sum();
            int sumB = maps.stream().filter(item ->
                    StringUtils.equals(questionsId, ObjectUtil.toString(item.get("QUESTIONS_ID"))) && StringUtils.equals("B", ObjectUtil.toString(item.get("USERANSWER")))
            ).mapToInt(item -> Integer.parseInt(ObjectUtil.toString(item.get("COUNT")))).sum();
            int sumC = maps.stream().filter(item ->
                    StringUtils.equals(questionsId, ObjectUtil.toString(item.get("QUESTIONS_ID"))) && StringUtils.equals("C", ObjectUtil.toString(item.get("USERANSWER")))
            ).mapToInt(item -> Integer.parseInt(ObjectUtil.toString(item.get("COUNT")))).sum();
            int sumD = maps.stream().filter(item ->
                    StringUtils.equals(questionsId, ObjectUtil.toString(item.get("QUESTIONS_ID"))) && StringUtils.equals("D", ObjectUtil.toString(item.get("USERANSWER")))
            ).mapToInt(item -> Integer.parseInt(ObjectUtil.toString(item.get("COUNT")))).sum();

            BigDecimal proportion = new BigDecimal("100");

            Map<String, Object> temp = new HashMap<>();

            //各类型选择总数
            BigDecimal typeCount = new BigDecimal(sumA + sumB + sumC + sumD);
            //调查内容
            temp.put("title", title);
            //A人数
            temp.put("type_A", sumA);
            //A占比
            temp.put("percentage_A", new BigDecimal(sumA).divide(typeCount, 2, RoundingMode.HALF_UP).multiply(proportion).intValue());

            //B人数
            temp.put("type_B", sumB);
            //B占比
            temp.put("percentage_B", new BigDecimal(sumB).divide(typeCount, 2, RoundingMode.HALF_UP).multiply(proportion).intValue());
            //C人数
            temp.put("type_C", sumC);
            //C占比
            temp.put("percentage_C", new BigDecimal(sumC).divide(typeCount, 2, RoundingMode.HALF_UP).multiply(proportion).intValue());
            //D人数
            temp.put("type_D", sumD);
            //D占比
            temp.put("percentage_D", new BigDecimal(sumD).divide(typeCount, 2, RoundingMode.HALF_UP).multiply(proportion).intValue());
            result.add(temp);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> statisticsInterlocution(String testpaperId, Long orgId) {
        return testpaperMapper.statisticsInterlocution(testpaperId, orgId);
    }
}

